package com.gzhryc.common.logging;

import com.gzhryc.common.json.JsonTools;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogAnalysisUtils {

	static Pattern pat = Pattern.compile("\\{\\{([^}]+)\\}\\}");
	
	public static String out(String msg,Object...objs) {
		if(StringUtils.isNotBlank(msg) && objs != null && objs.length > 0) {
			Matcher mat = pat.matcher(msg);
			int mat_start = 0;
			while (mat.find(mat_start)){
				String str = mat.group(1);
			    if(str.contains(":")) {
			    	String[] temp = str.split(":");
			    	int i = Integer.valueOf(temp[0]);
			    	if(i < objs.length) {
			    		Object obj = objs[i];
			    		if(obj != null) {
					    	if("json".equals(temp[1])) {
					    		msg = msg.replace("{{"+str+"}}", JsonTools.toJson(obj));
					    	}else {
								msg = msg.replace("{{" + str + "}}", objToString(obj));
					    	}
			    		}else {
			    			msg = msg.replace("{{"+str+"}}", "NULL");
			    		}
			    	}
			    }else {
			    	int i = Integer.valueOf(str);
			    	if(i < objs.length) {
			    		Object obj = objs[i];
			    		if(obj != null) {
							msg = msg.replace("{{" + str + "}}", objToString(obj));
			    		}else {
			    			msg = msg.replace("{{"+str+"}}", "NULL");
			    		}
			    	}
			    }
			    mat_start = mat.end();
			}

			//安全检查，替换类似：${jndi:rmi:...，这样的注入
			msg = msg.replace("${","(%24%7B)");

		}
		return msg;
	}

	public static String out(String msg, Map<String,Object> objs) {
		if(StringUtils.isNotBlank(msg) && objs != null && objs.size() > 0) {
			Matcher mat = pat.matcher(msg);
			int mat_start = 0;
			while (mat.find(mat_start)){
				String str = mat.group(1);
				Object obj = objs.get(str);
				if(obj != null) {
					msg = msg.replace("{{" + str + "}}", objToString(obj));
				}else {
					msg = msg.replace("{{"+str+"}}", "NULL");
				}
				mat_start = mat.end();
			}

			//安全检查，替换类似：${jndi:rmi:...，这样的注入
			msg = msg.replace("${","(%24%7B)");
		}
		return msg;
	}

	private static String objToString(Object obj){
		if(Date.class.isInstance(obj)){
			String temp = null;
			try {
				return DateFormatUtils.format(Date.class.cast(obj), "yyyy-MM-dd HH:mm:ss");
			}catch (Exception e){}
		}
		return obj.toString();
	}
}
